from appserver import db_store
from sqlalchemy.sql import func
from models.entity.sensor import Sensor
from sqlalchemy import or_


class SensorType(db_store.Model):
    __tablename__ = "sensor_types"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'传感器类型名称')
    code = db_store.Column(db_store.String(32), nullable=False, unique=True, comment=u"传感器类型编码")
    description = db_store.Column(db_store.String(255), comment=u"描述")
    dis_order = db_store.Column(db_store.Integer, comment=u"排序",default=0)
    icon = db_store.Column(db_store.String(32), comment="图标")
    sensor = db_store.relationship('Sensor', backref='sensor', lazy='dynamic')

    def __repr__(self):
        return "<SensorType %s>" % self.name

    def get_max_id(self):
        val = db_store.session.query(func.max(SensorType.id)).scalar()
        if not val:
            return 0
        else:
            return val

    def save(self):

        if self.id is None:
            self.id = self.get_max_id() + 1
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print("error is " + e)
            db_store.session.rollback()
            return False

    def delete(self):# delete只做删除功能，其他功能不做
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print(e)
            db_store.session.rollback()
            return False
    
    def get_dic(self):
        rdic={}
        rdic["id"]=self.id
        rdic["name"]=self.name
        rdic["code"]=self.code
        rdic["description"]=self.description
        rdic["dis_order"]=self.dis_order
        rdic["icon"]=self.icon
        sensor_num=len(Sensor.query.filter_by(sensor_type_id=self.id).all())
        rdic["sensor_num"]=sensor_num
        return rdic

    @staticmethod
    def get_sensor_type_all():
        return SensorType.query.order_by("dis_order").all()

    @staticmethod
    def search(query_word):
        tmp = {}
        data = []
        sensor_types = SensorType.query.filter(
            or_(SensorType.code.like('%' + query_word + '%'), SensorType.name.like('%' + query_word + '%'),
                SensorType.description.like('%' + query_word + '%'),SensorType.dis_order.like('%'+query_word+'%'))).order_by("dis_order").all()
        for obj in sensor_types:
            data.append(obj.to_dict())
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return tmp
